package com.compass.doctor.ui.home

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnCreateConsumableCallBack
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.databinding.ActivityCompleteOrderBinding
import com.compass.doctor.dialog.CompleteOrderCodeDialog
import com.compass.doctor.dialog.ConsumableOrderDialog
import com.compass.doctor.preview.PreviewPicActivity
import com.compass.doctor.ui.home.adapter.ConsumableOrderAdapter
import com.compass.doctor.ui.home.adapter.GridImageAdapter
import com.compass.doctor.ui.home.adapter.GridImageAdapter.OnItemClickListener
import com.compass.doctor.ui.home.viewmodel.MedicalCareViewModel
import com.compass.doctor.utils.SelectPicturesUtil
import com.compass.framework.R
import com.compass.framework.constant.KEY_CARE_ORDER
import com.compass.framework.constant.KEY_ORDER_ID
import com.compass.framework.constant.REFRESH_CARE
import com.compass.framework.constant.REFRESH_MESSAGE
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.glide.setUrlCircle
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.model.CreateConsumable
import com.compass.framework.model.MedicalCareOrder
import com.compass.framework.model.NurseFinish
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.FullyGridLayoutManager
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.MoneyInputFilter
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.netease.yunxin.kit.chatkit.ui.common.MessageDialog
import java.io.File
import java.lang.ref.WeakReference

/**
 * Description： 医护订单/完成订单
 * Date:2024/1/2 10:06
 */
class MedicalCareCompleteOrderActivity : BaseVBActivity<ActivityCompleteOrderBinding>() {


    companion object {
        fun start(context: Context, orderId: String, careOrder: MedicalCareOrder) {
            val intent = Intent(context, MedicalCareCompleteOrderActivity::class.java)
            intent.putExtra(KEY_ORDER_ID, orderId)
            intent.putExtra(KEY_CARE_ORDER, careOrder)
            context.startActivity(intent)
        }
    }

    private var careOrder: MedicalCareOrder? = null
    private lateinit var orderId: String
    private var wxCode: String? = null
    private val medicalCareViewModel: MedicalCareViewModel by viewModels()
    private var success: MutableList<String> = mutableListOf()//上传成功的集合
    private var fails: MutableList<String> = mutableListOf()//上传成功的集合
    private lateinit var nurseFinish: NurseFinish
    private val maxSelectNum = 9
    private var mPic: List<LocalMedia> = ArrayList()
    private lateinit var mAdapter: GridImageAdapter
    private var index: Int = 0//记录下标（从第一张开始）
    private val weakHandler by lazy { WeakReferenceHandler(this) }
    private var consumableOrderDialog: ConsumableOrderDialog.Builder? = null
    private var oderCodeDialog: CompleteOrderCodeDialog.Builder? = null//二维码弹窗

    private lateinit var consumableOrderAdapter: ConsumableOrderAdapter
    private var isSubmit: Boolean = false//正在提交

    //耗材添加回调
    private var consumableOrderClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(position: Int, msgType: String?) {
            val item = consumableOrderAdapter.getItem(position)

            when (msgType) {
                "delete" -> {
                    CommonMessageDialog.Builder(this@MedicalCareCompleteOrderActivity)
                        .setTitle(getStringFromResource(R.string.dialog_tips_title))
                        .setMessage("是否确定删除当前订单？")
                        .setConfirm(getStringFromResource(R.string.default_confirm))

                        .setCancel(getString(com.compass.framework.R.string.default_cancel))
                        .setonCancelListener {
                            it?.dismiss()
                        }
                        .setonConfirmListener {
                            item?.let { order ->
                                medicalCareViewModel.deleteConsumableOrder(order.id)
                            }

                            it?.dismiss()
                        }.create().show()
                }

                "wxCode" -> {
                    item?.let { order ->
                        showLoading()
                        medicalCareViewModel.consumableOrderPay(order.id)
                    }

                }

            }
        }
    }


    private var onCreateConsumableCallBack = object : OnCreateConsumableCallBack {
        override fun createConsumableCallBack(consumable: CreateConsumable) {
            showLoading()
            medicalCareViewModel.createConsumable(consumable)


        }
    }

    class WeakReferenceHandler(obj: MedicalCareCompleteOrderActivity) :
        Handler(Looper.getMainLooper()) {

        private val mRef: WeakReference<MedicalCareCompleteOrderActivity> = WeakReference(obj)
        override fun handleMessage(msg: Message) {
            mRef.get()?.run {
                when (msg.what) {
                    1 -> {
                        //上传操作
                        medicalCareViewModel.upload(File(mPic[index].compressPath))
                    }

                    2 -> {
                        //完成操作
                        nurseFinish = NurseFinish(
                            orderId,
                            temperature,
                            breathing,
                            heartRate,
                            sbp,
                            dbp,
                            log,
                            success
                        )
                        medicalCareViewModel.nurseFinish(nurseFinish)
                    }

                    3 -> {
                        //失败
                        dismissLoading()
                        isSubmit = false
                        showToast("图片上传失败")
                    }
                }
            }
        }
    }

    private fun setPatientInfo() {
        careOrder?.let {
            mBinding.authentication.text = it.nurseName

            mBinding.ivHead.setUrlCircle(it.patientAvatar)
            mBinding.patientName.text = it.patientName
            mBinding.usefulSex.text = it.getSexString()
            mBinding.usefulAge.text = it.patientAge
        }

    }

    override fun initView(savedInstanceState: Bundle?) {
        orderId = intent.getStringExtra(KEY_ORDER_ID)!!
        careOrder = intent.serializable(KEY_CARE_ORDER)
        setPatientInfo()
        consumableOrderAdapter = ConsumableOrderAdapter()
        consumableOrderAdapter.setCustomBottomClick(consumableOrderClick)
        mAdapter = GridImageAdapter(this, mPic)
        mAdapter.selectMax = maxSelectNum
        mBinding.recycler.apply {
            val manager = FullyGridLayoutManager(
                this@MedicalCareCompleteOrderActivity,
                4, FullyGridLayoutManager.VERTICAL, false
            )
            layoutManager = manager
            itemAnimator?.let {
                (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
            }
            adapter = mAdapter
        }
        mBinding.rcyConsumable.apply {
            layoutManager = LinearLayoutManager(context)

            adapter = consumableOrderAdapter
            addItemDecoration(NormalItemDecoration().apply {
                setBounds(top = dpToPx(10), bottom = dpToPx(10))

            })
        }

        mBinding.tvRefuse.onClick {
            showConsumableOrderDialog()
        }
        //体温
        val filter = MoneyInputFilter()
        filter.setMaxValue(50.0)
        filter.setDecimalLength(2)
        mBinding.edtTemperature.filters = arrayOf(filter)

        //呼吸次数
        val filterBreath = MoneyInputFilter()
        filterBreath.setMaxValue(100.0)
        filterBreath.setDecimalLength(0)
        mBinding.edtBreathing.filters = arrayOf(filterBreath)

        //心率
        val filterHeart = MoneyInputFilter()
        filterHeart.setMaxValue(300.0)
        filterHeart.setDecimalLength(0)
        mBinding.edtHeartRate.filters = arrayOf(filterHeart)
        //舒张压
        val filterDbp = MoneyInputFilter()
        filterDbp.setMaxValue(300.0)
        filterDbp.setDecimalLength(0)
        mBinding.edtDbp.filters = arrayOf(filterDbp)

        //收缩压
        val filterSbp = MoneyInputFilter()
        filterSbp.setMaxValue(300.0)
        filterSbp.setDecimalLength(0)
        mBinding.edtSbp.filters = arrayOf(filterSbp)
        setSupportNewOrder()

    }


    private fun setSupportNewOrder() {
        if (UserInfoManager.getUserInfo()?.appHospitalConfigRespVO?.isSupportNewOrder == "1") {
            mBinding.tvRefuse.visible()
            mBinding.clyOrder.visible()
        } else {
            mBinding.tvRefuse.gone()
            mBinding.clyOrder.gone()
        }

    }

    private fun showConsumableOrderDialog() {
        consumableOrderDialog =
            ConsumableOrderDialog.Builder(this, orderId, onCreateConsumableCallBack)
        consumableOrderDialog?.show()
    }

    override fun intListener() {

        mAdapter.setOnItemClickListener(object : OnItemClickListener {
            override fun openPicture() {
                isReadWriteGranted()
            }

            override fun onItemClick(v: View?, position: Int) {
                PreviewPicActivity.start(
                    this@MedicalCareCompleteOrderActivity,
                    position,
                    mAdapter.data
                )
            }
        })

        mBinding.tvAccept.onClick {
            isHaveConsumableOrder()

        }
    }


    /**
     * 判断是否有耗材订单
     */
    private var isHaveConsumableOrderTips: Boolean = false //判断是否有耗材订单提示

    private fun isHaveConsumableOrder() {
        if (!isHaveConsumableOrderTips && consumableOrderAdapter.getData().isEmpty()) {
            isHaveConsumableOrderTips = true
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(com.compass.framework.R.string.dialog_tips_title))
                .setMessage("您还没有添加耗材订单，是否需要添加耗材订单？")
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))

                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    showConsumableOrderDialog()
                    it?.dismiss()
                }.create().show()


        } else {
            setData()
        }


    }

    override fun initData() {
        showLoading()
        medicalCareViewModel.getConsumableOrder(orderId)
        medicalCareViewModel.consumableOrderLiveData.observe(this) {
            consumableOrderAdapter.setData(it)
            dismissLoading()

        }
        medicalCareViewModel.deleteOrderLiveData.observe(this) {
            medicalCareViewModel.getConsumableOrder(orderId)
        }

        medicalCareViewModel.createConsumableLiveData.observe(this) {
            it?.let {
                showPayDialog(it)
                medicalCareViewModel.getConsumableOrder(orderId)
            }
            dismissLoading()
        }

        medicalCareViewModel.payCodeLiveData.observe(this) {
            showPayDialog(it)

        }
        medicalCareViewModel.updateLiveData.observe(this) {
            it?.let {
                success.add(it)
                index++
                if (index < mPic.size) {
                    //继续上传
                    weakHandler.sendEmptyMessage(1)
                } else {
                    //结束上传
                    weakHandler.sendEmptyMessage(2)
                }
            } ?: kotlin.run {
                //失败
                weakHandler.sendEmptyMessage(3)
                fails.add(mPic[index].compressPath)//后续优化失败续传
            }
        }

        medicalCareViewModel.finishLiveData.observe(this) {
            isSubmit = false
            dismissLoading()
            LiveDataBus.get().with(REFRESH_CARE).postValue(REFRESH_CARE)
            showToast("提交成功")
            finish()
        }

        LiveDataBus.get().with(REFRESH_MESSAGE, String::class.java)
            .observe(this) {
                //接收 支付成功通知
                oderCodeDialog?.dismissDialog()
                medicalCareViewModel.getConsumableOrder(orderId)
            }

    }

    private lateinit var temperature: String
    private lateinit var breathing: String
    private lateinit var heartRate: String
    private lateinit var dbp: String
    private lateinit var sbp: String
    private lateinit var log: String
    private fun setData() {
        if (isSubmit) {
            showToast("正在提交数据,请勿重复点击")
            return
        }


        temperature = mBinding.edtTemperature.text.toString().trim()
        if (temperature.isEmpty()) {
            showToast("请输入体温")
            return
        }
        breathing = mBinding.edtBreathing.text.toString().trim()
        if (breathing.isEmpty()) {
            showToast("请输入呼吸次数")
            return
        }
        heartRate = mBinding.edtHeartRate.text.toString().trim()
        if (heartRate.isEmpty()) {
            showToast("请输入心率")
            return
        }
        dbp = mBinding.edtDbp.text.toString().trim()//舒张压
        if (dbp.isEmpty()) {
            showToast("请输入舒张压")
            return
        }
        sbp = mBinding.edtSbp.text.toString().trim()//收缩压
        if (sbp.isEmpty()) {
            showToast("请输入收缩压")
            return
        }
        log = mBinding.edtInformation.text.toString().trim()
        if (log.isEmpty()) {
            showToast("请输入护理日志")
            return
        }
        if (log.length < 15) {
            showToast("请至少输入15个字")
            return
        }


        if (mPic.isNotEmpty()) {
            isSubmit = true
            showLoading("正在上传图片...")
            index = 0
            weakHandler.sendEmptyMessage(1)
            return
        } else {
            showToast("请上传日志图片")
            return
        }


    }

    /**
     * 判断是否有读写拍照等权限
     */
    private fun isReadWriteGranted() {
        //判断是否有权限
        if (XXPermissions.isGranted(this, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE,Permission.CAMERA)) {
            choosePic()
        } else {
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(com.compass.doctor.R.string.permission_explain))
                .setMessage(getStringFromResource(com.compass.doctor.R.string.image_permission_logs))
                .setConfirm(getStringFromResource(R.string.default_confirm))
                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    requestPermissions()
                    it?.dismiss()
                }.create().show()
        }
    }


    /**
     * 请求权限
     */
    private fun requestPermissions() {
        XXPermissions.with(this)
            .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .permission(Permission.CAMERA)
            .unchecked()
            .request(object : OnPermissionCallback {

                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips("获取部分权限成功，但部分权限未正常授予")
                        return
                    }
                    choosePic()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {

                        TipsToast.showTips("被永久拒绝授权，请手动授予相关权限")
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(
                            this@MedicalCareCompleteOrderActivity,
                            permissions
                        )
                    } else {
                        TipsToast.showTips(com.compass.doctor.R.string.default_agree_permission)
                    }
                }
            })
    }

    /**
     * 选择图片
     */
    private fun choosePic() {
        SelectPicturesUtil.selectPicturesMultiple(
            this@MedicalCareCompleteOrderActivity, mAdapter.data,
            callbackListener = object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: ArrayList<LocalMedia?>) {
                    val isMaxSize = result.size == mAdapter.selectMax
                    val oldSize: Int = mAdapter.data.size
                    mAdapter.notifyItemRangeRemoved(
                        0,
                        if (isMaxSize) oldSize + 1 else oldSize
                    )
                    mAdapter.data.clear()
                    mAdapter.data.addAll(result)
                    mPic = mAdapter.data
                    mAdapter.notifyItemRangeInserted(0, result.size)
                }

                override fun onCancel() {

                }
            })
    }

    private fun showPayDialog(wxString: String?) {
        consumableOrderDialog?.dismissDialog()
        dismissLoading()
        wxString?.let {
            wxCode = it
            oderCodeDialog = CompleteOrderCodeDialog.Builder(this, wxCode)
            oderCodeDialog?.show()
        }
    }
}